package org.example.seckill.consumer.listener;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.example.seckill.dao.pojo.Order;
import org.example.seckill.service.OrderService;
import org.example.seckill.service.SeckillService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RocketMQMessageListener(
        topic = "tp_seckill_order_01",
        consumerGroup = "seckill_order_consumer_grp_01",
        selectorExpression = "create_order"
)
public class SeckillCreateOrderListener implements RocketMQListener<String> {

    @Autowired
    private OrderService orderService;

    @Autowired
    private SeckillService seckillService;

    @Override
    public void onMessage(String message) {
        log.info(message);
        String[] parts = message.split(":");
        Order order = orderService.createOrder(Integer.valueOf(parts[0]), Integer.valueOf(parts[1]));

        // 发送延迟消息定时删除订单
        try {
            seckillService.sendExpireOrderMsg(order);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
